package com.wu.foodsafetyplayer.utils

import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.google.gson.Gson
import com.wu.foodsafetyplayer.Application
import com.wu.foodsafetyplayer.app.bean.UserEntity

object SpUtil {


    @JvmStatic
    fun preferences(): SharedPreferences {
        return PreferenceManager.getDefaultSharedPreferences(Application.getAppContext())
    }

    @JvmStatic
    fun editor(): SharedPreferences.Editor {
        return PreferenceManager.getDefaultSharedPreferences(Application.getAppContext()).edit()
    }

    @JvmStatic
    fun clear(){
        editor().clear().commit()
    }

    /**
     * 获取boolean值
     * @param key
     * @param defaultValue
     * @return
     */
    @JvmStatic
    fun getBoolean(key: String, defaultValue: Boolean): Boolean {
        return preferences().getBoolean(key, defaultValue)
    }

    /**
     * 保存boolean值
     * @param key
     * @param value
     */
    @JvmStatic
    fun saveBoolean(key: String, value: Boolean) {
        editor().putBoolean(key, value).apply()
    }
    /**
     * 获取string值
     * @param key
     * @return
     */
    fun getStringValue(key: String): String? {
        return preferences().getString(key, null)
    }
    /**
     * 保存string值
     * @param key
     * @param value
     */
    fun saveStringValue(key: String, value: String) {
        editor().putString(key, value).apply()
    }

    fun clearByKey(key: String){
        editor().remove(key).apply()
    }

    private val gson: Gson by lazy { Gson() }
    private val UserInfo = "UserInfo"
    private var userEntity: UserEntity? = null
    fun saveUserInfo(user: UserEntity) {
        userEntity = user
        if (userEntity == null) {
            editor().remove(UserInfo).apply()
        } else {
            editor().putString(UserInfo, gson.toJson(user)).apply()
        }
    }

    fun clearUserInfo(){
        editor().remove(UserInfo).apply()
        editor().commit()
    }

    fun getUserInfo(): UserEntity {
        try {
            if (userEntity == null) {
                val value = preferences().getString(UserInfo, null)!!
                userEntity = gson.fromJson(value, UserEntity::class.java)
            }
        } catch (e: Exception) {
            //LogUtils.e(e)
        }
        return userEntity ?: UserEntity().apply { isnoLogin = true }
    }
}